package com.ecube.maintenance.components.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.baidu.lbsapi.auth.LBSAuthManagerListener;
import com.baidu.navisdk.BNaviEngineManager;
import com.baidu.navisdk.BaiduNaviManager;
import com.ecube.maintenance.R;
import com.ecube.maintenance.biz.apis.impl.SellerAction;
import com.ecube.maintenance.biz.commons.ICCallBack;
import com.ecube.maintenance.biz.commons.ICTException;
import com.ecube.maintenance.biz.commons.VolleySingleton;
import com.ecube.maintenance.components.activity.BaiduMapLocActivity;
import com.ecube.maintenance.components.application.CCBApplication;
import com.ecube.maintenance.components.widget.AutoSwitchText;
import com.ecube.maintenance.components.widget.LoadingDialog;
import com.ecube.maintenance.pojos.AddressInfo;
import com.ecube.maintenance.pojos.ProductInfo;
import com.ecube.maintenance.pojos.SellerInfo;
import com.ecube.maintenance.pojos.UserInfo;
import com.ecube.maintenance.utils.Bog;
import com.ecube.maintenance.utils.ListUtil;
import com.ecube.maintenance.utils.ScrollListUtil;

import java.util.List;

public class DealerDetailFragment extends CustomFragment {
    private static final String ARG_DATE = "date";
    private static final String ARG_SELLER_INFO = "seller_info";

    AutoSwitchText autoSwitchText;

    UserInfo userInfo = UserInfo.getInstance();
    SellerInfo sellerInfo = null;
    String mDate;
    ImagePagerAdapter viewPagerAdapter;
    ItemListAdapter itemListAdapter;//工位列表适配器

    TextView mAddressTextView, mDateTextView,mIndicatorView;
    ListView mItemList;
    TextView mLimitTextView;
    Button mAskButton;
    ViewPager viewPager;

    int seeItemAtPosition = -1;
    private boolean mIsEngineInitSuccess = false;
    private BNaviEngineManager.NaviEngineInitListener mNaviEngineInitListener = new BNaviEngineManager.NaviEngineInitListener() {
        public void engineInitSuccess() {
            //导航初始化是异步的，需要一小段时间，以这个标志来识别引擎是否初始化成功，为true时候才能发起导航
            mIsEngineInitSuccess = true;
        }

        public void engineInitStart() {
        }

        public void engineInitFail() {
        }
    };

    public DealerDetailFragment() {
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param date id of dealer.
     * @return A new instance of fragment DealerDetailFragment.
     */

    public static DealerDetailFragment newInstance(String date, SellerInfo info) {
        DealerDetailFragment fragment = new DealerDetailFragment();
        Bundle args = new Bundle();
        args.putString(ARG_DATE, date);
        args.putSerializable(ARG_SELLER_INFO, info);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
        initBaiduNavi();
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mDate = getArguments().getString(ARG_DATE);
            sellerInfo = (SellerInfo) getArguments().getSerializable(ARG_SELLER_INFO);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_dealer_detail, container, false);
        mAskButton = (Button) rootView.findViewById(R.id.ask_production);
        mAskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                askProduction();
            }
        });
//        mAskButton.setVisibility(View.GONE);
        mItemList = (ListView) rootView.findViewById(R.id.item_detail_list);
        itemListAdapter = new ItemListAdapter(getActivity());
        mItemList.setAdapter(itemListAdapter);
        ScrollListUtil.setListViewHeightBasedOnChildren(mItemList);
        mIndicatorView = (TextView) rootView.findViewById(R.id.viewpager_indicator);
        viewPager = (ViewPager) rootView.findViewById(R.id.show_pager);
        mAddressTextView = (TextView) rootView.findViewById(R.id.seller_detail_address_name);

        mDateTextView = (TextView) rootView.findViewById(R.id.detail_of_date);
        mDateTextView.setText(mDate);
        mLimitTextView = (TextView) rootView.findViewById(R.id.limit_text);
        setLimitTextView();
        viewPagerAdapter = new ImagePagerAdapter(getActivity());
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {
            }

            @Override
            public void onPageSelected(int i) {
                setIndicatorText(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
        autoSwitchText = (AutoSwitchText) rootView.findViewById(R.id.text_auto_switch_detail);
        loadDetails();
        return rootView;
    }

    void setIndicatorText(int pos) {
        mIndicatorView.setText((pos + 1) + "/" + viewPagerAdapter.getCount());
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
/*        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }*/
    }

    private ActionBar getActionBar() {
        return getActivity().getActionBar();
    }

    //求工位

    @Override
    public void onDestroy() {
        super.onDestroy();
        autoSwitchText.removeCallBack();
    }

    //加载详细数据

    @Override
    public void onResume() {
        super.onResume();
        configureActionBar();
    }

    private void askProduction() {
        userInfo = UserInfo.getInstance();
        if (TextUtils.isEmpty(userInfo.getSid())) {
            goLogin();
            return;
        }
        final LoadingDialog dialog = new LoadingDialog(getActivity());
        dialog.show();
        SellerAction.claimProduct(userInfo.getSid(), sellerInfo.getSpID(),
                CCBApplication.sAddressInfo, new ICCallBack() {
                    @Override
                    public void done(Object result, ICTException exception) {
                        dialog.getDialog().dismissDialogger();
                        if (exception == null) {
                            Bog.toast(R.string.message_ask_production_success);
                        } else {
                            Bog.toast( exception.getMessage());
                        }
                    }
                });

    }

    private void loadDetails() {

        if (sellerInfo == null) return;
        final LoadingDialog dialog = new LoadingDialog(getActivity());
        dialog.setTipText(getString(R.string.message_loading_seller_detail));
        dialog.show();
        SellerAction.fetchSellerDetail(userInfo.getSid(), sellerInfo.getSpID(), mDate,
                new ICCallBack<SellerInfo>() {

                    @Override
                    public void done(SellerInfo result, ICTException exception) {
                        dialog.getDialog().dismissDialogger();
                        if (exception == null) {
                            sellerInfo = result;
                            mAddressTextView.setText(sellerInfo.getAddress());
                            viewPagerAdapter.refreshImages();
                            itemListAdapter.refresh();
                            if (result.getProductList().size() == 0)
                                mAskButton.setVisibility(View.VISIBLE);
                            mAddressTextView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
//                                    AddressInfo addressInfo = new AddressInfo();
//                                    addressInfo.setLat(sellerInfo.getLat());
//                                    addressInfo.setLon(sellerInfo.getLon());
//                                    addressInfo.setAddress(sellerInfo.getAddress());
//                                    Uri uri = Uri.parse(
//                                            "geo:" + addressInfo.getLat() + "," + addressInfo.getLon() +
//                                                    "?q=" + addressInfo.getLat() + "," + addressInfo.getLon() +
//                                                    "(4s店位置)?z=15");
//                                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//                                    startActivity(intent);
                                    launchLocation();
                                }
                            });
                            setLimitTextView();
                            if (ListUtil.isEmpty(sellerInfo.getRollText())) {
//                                autoSwitchText.setVisibility(View.INVISIBLE);
                            } else {
//                                autoSwitchText.setVisibility(View.VISIBLE);
                                autoSwitchText.setTexts(sellerInfo.getRollText());
                            }

                        } else {
                            Bog.toast(getString(R.string.message_no_available_network));
                            getFragmentManager().popBackStack();
                        }
                    }
                });
    }

    void setLimitTextView() {
        int d = 0;
        int l = 0;

        if (sellerInfo != null) {
            d = sellerInfo.getDailyLimit();
            l = sellerInfo.getLeftLimit();
        }

        mLimitTextView.setText(d + "个名额" + "，还剩" + l + "个名额");
    }

    private void configureActionBar() {
        ActionBar actionBar = getActionBar();
        assert actionBar != null;
        /*View v = actionBar.getCustomView();
        if (v != null) {
            v.setVisibility(View.GONE);
        }*/
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    getActionBar().getCustomView().setVisibility(View.GONE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 1);
        actionBar.setDisplayShowTitleEnabled(true);
        String title = "商家信息";

        if (sellerInfo != null) {
            title = sellerInfo.getSpName();
        }
        actionBar.setTitle(title);
        setFragmentTitle(title);
    }

    void goLogin() {
        Bog.toast("请先注册登录");
        getFragmentManager().beginTransaction().hide(DealerDetailFragment.this)
                .add(R.id.container,
                        LoginFragment.newInstance()
                ).addToBackStack(null)
                .commit();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        configureActionBar();
        super.onHiddenChanged(hidden);
    }

    void initBaiduNavi(){
        BaiduNaviManager.getInstance().
                initEngine(getActivity(),getSdcardDir(),mNaviEngineInitListener,
                        new LBSAuthManagerListener() {
                    @Override
                    public void onAuthResult(int i, String s) {

                    }
                });
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(
                Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    /**
     * 指定导航起终点启动GPS导航.起终点可为多种类型坐标系的地理坐标。
     * 前置条件：导航引擎初始化成功
     */
    private void launchLocation(){
        try{
            AddressInfo from = CCBApplication.sAddressInfo;
            AddressInfo to = new AddressInfo();
            to.setAddress(sellerInfo.getAddress());
            to.setLon(sellerInfo.getLon());
            to.setLat(sellerInfo.getLat());
            BaiduMapLocActivity.displayMyselfFromFragment(this,from,to);
        } catch (Exception e) {
            Bog.toast("启动地图导航失败.");
        }
    }

    private class ItemListAdapter extends BaseAdapter {
        LayoutInflater inflater;
        List<ProductInfo> infos;

        public ItemListAdapter(Context context) {
            this.inflater = LayoutInflater.from(context);
        }


        public void refresh() {
            if (sellerInfo != null) {
                infos = sellerInfo.getProductList();
                notifyDataSetChanged();
                ScrollListUtil.setListViewHeightBasedOnChildren(mItemList);
            }

            if (itemListAdapter.getCount() != 0) {
                mAskButton.setVisibility(View.GONE);
                mItemList.setVisibility(View.VISIBLE);
            } else {
                mItemList.setVisibility(View.GONE);
                mAskButton.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public int getCount() {
            return infos == null ? 0 : infos.size();
        }

        @Override
        public Object getItem(int position) {
            return infos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.adapter_detail_production_item, null);
                holder.orderBtn = (Button) convertView.findViewById(R.id.order_right_now);
                holder.serviceDetailLayout = (LinearLayout) convertView.findViewById(R.id.service_details_layout);
                holder.serviceDetails = (TextView) convertView.findViewById(R.id.service_details_items);
                holder.serviceName = (TextView) convertView.findViewById(R.id.service_name);
                holder.serviceOriginPrice = (TextView) convertView.findViewById(R.id.service_originprice);
                holder.serviceDiscountPrice = (TextView) convertView.findViewById(R.id.service_discountprice);
                holder.serviceTime = (TextView) convertView.findViewById(R.id.service_time);
                holder.serviceRootLayout = (LinearLayout) convertView.findViewById(R.id.service_detail_product_root);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final ProductInfo info = infos.get(position);
            holder.serviceName.setText(info.getProductName());
            StringBuffer sb = new StringBuffer();
            sb.append(info.getServiceStartTime()).append("\n~\n").append(info.getServiceEndTime());
            holder.serviceTime.setText(sb);
            String origPrice = null;
            String discountPrice = null;

            if (false) {
                origPrice = "已预订";
                discountPrice = "无";
//                autoSwitchText.setPaintFlags(autoSwitchText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
                origPrice = info.getOrigPrice();

                discountPrice = info.getDiscountPrice();
                holder.serviceOriginPrice.setPaintFlags(autoSwitchText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }

            holder.serviceDiscountPrice.setText("￥" + discountPrice);
            holder.serviceOriginPrice.setText("￥" + origPrice);
            StringBuffer details = new StringBuffer();
            int cnt = info.getServiceItems() == null ? 0 : info.getServiceItems().size();

            for (int i = 0; i < cnt; i++) {
                details.append((i + 1) + ". ").append(info.getServiceItems().get(i)).append("\n");
            }
            holder.serviceDetails.setText(details);
            holder.serviceRootLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (seeItemAtPosition == position) {
                        seeItemAtPosition = -1;
                    } else {
                        seeItemAtPosition = position;
                    }
                    refresh();
                    mItemList.smoothScrollToPosition(position);
                }
            });

            if (position == seeItemAtPosition) {
                holder.serviceDetailLayout.setVisibility(View.VISIBLE);
                holder.serviceRootLayout.setBackgroundResource(R.drawable.selector_ict_gray_bg);
            } else {
                holder.serviceDetailLayout.setVisibility(View.GONE);
                holder.serviceRootLayout.setBackgroundResource(R.drawable.selector_ict_white_bg);
            }

            if (sellerInfo.getLeftLimit() == 0) {
                holder.orderBtn.setEnabled(false);
            } else {
                holder.orderBtn.setEnabled(true);
            }
            holder.orderBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    userInfo = UserInfo.getInstance();
                    if (TextUtils.isEmpty(userInfo.getSid())) {
                        goLogin();
                        return;
                    }
                    getFragmentManager().beginTransaction().hide(DealerDetailFragment.this)
                            .add(R.id.container,
                                    OrderConfirmationFragment.newInstance(
                                            sellerInfo, info, mDate)
                            ).addToBackStack(null)
                            .commit();
                }
            });
            return convertView;
        }

        public class ViewHolder {


            TextView serviceTime, serviceName, serviceOriginPrice, serviceDiscountPrice, serviceDetails;
            LinearLayout serviceDetailLayout, serviceRootLayout;
            Button orderBtn;
        }
    }

    private class ImagePagerAdapter extends PagerAdapter {
        private List<String> image;
        private Context mContext;

        public ImagePagerAdapter(Context context) {
            this.mContext = context;

        }


        public void refreshImages() {
            if (sellerInfo != null) {
                image = sellerInfo.getImages();
                notifyDataSetChanged();
            }
            if(getCount() == 0){
                mIndicatorView.setVisibility(View.GONE);
                viewPager.setBackgroundResource(R.drawable.default_dealer_info_bg);
            } else {
                mIndicatorView.setVisibility(View.VISIBLE);
                viewPager.setBackgroundColor(getResources().getColor(R.color.transparent));
            }
            setIndicatorText(viewPager.getCurrentItem());
        }

        @Override
        public int getCount() {

            return image != null ? image.size() : 0;
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            ImageView view = (ImageView) LayoutInflater.from(mContext).inflate(R.layout.adapter_seller_detail_images_item, null);
            ImageLoader.ImageListener listener = ImageLoader.getImageListener(view, R.drawable.dealer_example, R.drawable.dealer_example);
            VolleySingleton.loadImage(image.get(position), listener);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
}
